import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ZhongJinTao
 * Date: 2024-03-15
 * Time: 8:49
 */
public class TcpEchoServer {
    ServerSocket socket = null;

    public TcpEchoServer(int serverPort) throws IOException {
        socket = new ServerSocket(serverPort);
    }

    public void start() throws IOException {
        System.out.println("服务器启动");
        while (true) {
            Socket  clientSocket = socket.accept();
            Thread t = new Thread(() -> {
                processConnection(clientSocket);
            });
            t.start();
        }
    }

    public void processConnection(Socket clientSocket) {
        System.out.printf("[%s : %d] 客户端上线\n", clientSocket.getInetAddress(), clientSocket.getPort());
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()) {
            while (true) {
                //1、读取响应
                Scanner scanner = new Scanner(inputStream);
                if(!scanner.hasNext()) {
                    System.out.printf("[%s : %d] 客户端下线\n", clientSocket.getInetAddress(),
                            clientSocket.getPort());
                    break;
                }
                String request = scanner.next();
                //2、计算响应
                String response = process(request);
                //3、返回响应
                PrintWriter writer = new PrintWriter(outputStream);
                writer.println(response);
                writer.flush();

                //打印日志
                System.out.printf("[%s : %d] res: %s resp: %s\n", clientSocket.getInetAddress(),
                        clientSocket.getPort(), request, response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer = new TcpEchoServer(9090);
        tcpEchoServer.start();
    }
}
